# -*- coding: utf-8 -*-

#自适应亮度均衡算法
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt

# def adapBrightBalance(im, num_block, diff, max_m, percent):
#     M = max_m
#     w,h = im.shape
#     C = w/num_block
#     arr_SL = np.zeros((h, num_block))
#     block = []
#     for i in range(num_block):
#         block.append(im[:, i*C:(i+1)*C])
#     for i in range(num_block):
#         block[i] = block[i][np.argsort(block[i], axis=1)]
#     for i in range(num_block):
#         arr_SL[:,i] = np.sum(block[i][:M])/M

#main
img = Image.open('57.png')
gray = img.convert('L')
im = np.array(gray)

M = 8
num_block = 20
w, h = im.shape
C = w / num_block
arr_SL = np.zeros((h, num_block))
block = []
for i in range(num_block):
    block.append(im[:, i * C:(i + 1) * C])
    b = block[i]
    for j in range(len(block[i])):
        b[j] = b[j][np.argsort(-b, axis=1)[j]]
        arr_SL[j, i] = np.sum(b[j,:][:M]) / M
AGC = np.ones(im.shape)
for i in range(num_block-1):
    for j in range(C):
        AGC[:, i*C+j] = (arr_SL[:, i]*(C-i) + arr_SL[:, i+1]*i)/C
AGC[AGC==0] = 240
BC = 240
AGC = BC/AGC



